package com.FH.organization.departmentCrp;

import com.FH.organization.people.KamMemberDAO;
import com.FH.util.AccessDB;
import com.FH.util.InternalInterface;
import com.FH.util.ResultDTO;
import com.FH.util.warnSrc;
import org.codehaus.jettison.json.JSONException;
import org.codehaus.jettison.json.JSONObject;

import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.inject.Inject;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * Created by ygg on 2016/6/28.
 *
 * 部门接口实现累
 *
 */

@Stateless
public class DepartmentCrpDAOImpl extends AccessDB implements DepartmentCrpDAO{

    @EJB
    private KamMemberDAO kamMemberDAO;
    @Inject
    DepartmentCrpResource departmentResource;




    /**
     * 获取部门信息
     * @param search
     * @param page
     * @param size
     * @return
     * 如果需要查询部门下的用户，请在search中传入isNeedUser参数
     */
    @Override
    public ResultDTO getDepartmentInfo(String search,String page,String size) {

        ResultDTO resultDTO = new ResultDTO();

        try {
            JSONObject json = new JSONObject(search);
            String existName = "0";

            String sqlexit = "select count(1) from organization  where 1=1 ";

            String sql_w ="";//查询条件sql组合

            String sql_page = "";//分页sql组合
            Integer page_ok = Integer.parseInt(page);
            Integer size_ok = Integer.parseInt(page);
            if(page.equals("1")){
                sql_page = " limit 0,"+size+"";
            }else{
                sql_page = " limit "+((page_ok-1)*size_ok+1)+","+size+"";
            }

            if(json.has("organization_id")){
//                sql_w += " AND organization_id = "+json.getString("organization_id");
                sql_w += " AND organization_id ='" + json.getString("organization_id") + "'";
            }
            if(json.has("organizationName")){
                sql_w += " AND organization_name like '%"+json.getString("organizationName") +"%'";
            }
            if(json.has("parent_organization_id")){
                sql_w += " AND parent_organization_id ="+json.getString("parent_organization_id");
            }
            String sql_ok = sqlexit+sql_w ;//组合好的sql语句
            existName = getReportingToOne(sql_ok);//查询此数据是否存在

            List<String []> seresult = new ArrayList<String []>();

            List<DepartmentCrpShowDTO> result = new ArrayList<DepartmentCrpShowDTO>();

            if(!existName.equals("0")){
                String sql ="SELECT organization_id,organization_name,parent_organization_id,organization_code,organization_state,is_leaf_,create_time_,creater_id,sort_no,status " +
                        " FROM organization WHERE 1=1 "+sql_w +sql_page;
                seresult = this.getReportingTo(sql);

                //构建返回对象
                for (int i = 0; i < seresult.size(); i++){

                    DepartmentCrpShowDTO department = new DepartmentCrpShowDTO();
                    department.setOrganization_id(seresult.get(i)[1]);
                    department.setOrganization_name(seresult.get(i)[2]);
                    department.setParent_organization_id(seresult.get(i)[3]);
                    department.setOrganization_code(seresult.get(i)[4]);
                    department.setOrganization_state(Integer.parseInt(seresult.get(i)[5]));
                    department.setIs_leaf(seresult.get(i)[6]);
                    department.setCreate_time(seresult.get(i)[7]);
                    department.setCreater_id(seresult.get(i)[8]);
                    department.setSort_no(Integer.parseInt(seresult.get(i)[9]));
                    department.setStatus(seresult.get(i)[10]);
                    if(json.has("isNeedUser")){
                        //获取该部门下的人员列表
                        String organization_id = seresult.get(i)[1];
                        ResultDTO userList ;
                        userList =kamMemberDAO.getUserListInfo("{organization_id:"+organization_id+"}","0","9999999");
                        department.setUser(userList.getValues());
                    }

                    result.add(department);

                }
            }


            if(seresult.size()!=0) {
                resultDTO.setStatus("90000");
                resultDTO.setDescritpion(warnSrc.get_success);
            }else {
                resultDTO.setStatus("90001");
                resultDTO.setDescritpion(warnSrc.get_fail);
            }

            resultDTO.setValues(result);

        } catch (JSONException e) {
            e.printStackTrace();
        }

        return resultDTO;

    }

    /**
     * 添加部门
     * @param str
     * @return
     */
    @Override
    public ResultDTO addDepartmentInfo(String str) {

        String strinfo[]=str.split("&");
        String strinfo1=strinfo[0];
        String strinfo2=strinfo[1];
        String strinfo3=strinfo[2];
        String strinfo4=strinfo[3];

        String fhId=strinfo1.split(":")[1];
        String pId=strinfo2.split(":")[1];
        String nodeName=strinfo3.split(":")[1];
        String isParent=strinfo4.split(":")[1];

        ResultDTO resultDTO = new ResultDTO();

        String sql = "select count(1) from organization WHERE base_org_id='"+fhId+"'";

        String sqlOne = getReportingToOne(sql);//插入前，查询是否有重复字段
            if(!sqlOne.equals("0")){
                return updateDepartmentInfo(str);
            }


            String sql_isHas = "select count(1) from organization WHERE organization_name='"+nodeName+"'";

            String existOrganization = getReportingToOne(sql_isHas);//插入前，查询是否有重复字段

            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//日期格式化

            String time = df.format(new Date());

            String uuid = UUID.randomUUID().toString().trim().replaceAll("-", "");

            int resultls = 0;


            if(existOrganization.equals("0")){

                String organization_insert = "";

                //构建插入sql
                organization_insert +="INSERT  INTO organization(organization_id,organization_name,isParent,base_org_id,PARENT_ORG_ID,create_time_) "+
                        "VALUES('"+uuid+"','"+nodeName+ "','" +isParent+"','"
                        +fhId+"','" +pId+ "','" +time+ "')";
                //插入业务表
                resultls =  addReportingTo(organization_insert);
            }

        if(resultls!=0) {
                resultDTO.setStatus("90000");
                resultDTO.setDescritpion(warnSrc.add_success);
            }else{
                resultDTO.setStatus("90001");
                resultDTO.setDescritpion(warnSrc.add_fail);
            }


        return resultDTO;
    }



    @Override
    public ResultDTO updateDepartmentInfo(String str) {

        String strinfo[]=str.split("&");
        String strinfo1=strinfo[0];
        String strinfo2=strinfo[1];
        String strinfo3=strinfo[2];
        String strinfo4=strinfo[3];


        String fhId=strinfo1.split(":")[1];
        String pId=strinfo2.split(":")[1];
        String nodeName=strinfo3.split(":")[1];
        String isParent=strinfo4.split(":")[1];

        ResultDTO resultDTO = new ResultDTO();

        String sql_isHas = "select count(1) from organization WHERE base_org_id='"+fhId+"'";

        String existOrganization = getReportingToOne(sql_isHas);//插入前，查询是否有重复字段

        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//日期格式化

        String time = df.format(new Date());

        String uuid = UUID.randomUUID().toString().trim().replaceAll("-", "");

        int resultls = 0;


        if (!existOrganization.equals("0")) {
            String QUERY = "";
            QUERY += "update organization set create_time_='" + time + "'";
            if (null != nodeName && !"".equals(nodeName)) {
                QUERY += ",organization_name='" + nodeName + "'";
            }

            if (null != pId && !"".equals(pId)) {
                QUERY += ",base_org_id='" + pId + "'";
            }
            if (null != isParent && !"".equals(isParent)) {
                QUERY += ",PARENT_ORG_ID='" + isParent + "'";
            }

            QUERY += "  where base_org_id='" + fhId + "'";

            resultls = addReportingTo(QUERY);
        }

        if(resultls!=0) {
            resultDTO.setStatus("90000");
            resultDTO.setDescritpion(warnSrc.add_success);
        }else{
            resultDTO.setStatus("90001");
            resultDTO.setDescritpion(warnSrc.add_fail);
        }


        return resultDTO;
    }

    @Override
    public ResultDTO deleteDepartmentInfo(String str) {
        String strinfo[]=str.split("&");
        String strinfo1=strinfo[0];


        String base_org_id=strinfo1.split(":")[1];



        //删除之前查询一下该表是否有记录
        String sql = "select count(1) from organization where base_org_id='" + base_org_id + "'";

        String existName = getReportingToOne(sql);

        int result = 0;

        if (!existName .equals(0)) {

            String QUERY = "";
            QUERY += "delete from organization where base_org_id='" + base_org_id + "'";

            result = this.addReportingTo(QUERY);
        }

        ResultDTO resultDTO = new ResultDTO();
        if (result != 0) {
            resultDTO.setStatus("90000");
            resultDTO.setDescritpion(warnSrc.delete_success);

        }
        else {
            resultDTO.setStatus("90001");
            resultDTO.setDescritpion(warnSrc.delete_fail);
        }
        return resultDTO;
    }

    /**
     * 回调到民师系统
     * @param departmentPullDTO
     * @return
     */
    @Override
    public ResultDTO addMhDepartmentInfo(DepartmentCrpPullDTO departmentPullDTO) {

        String  pId="";
        String json = "";
        try {
            String fhId = departmentPullDTO.getFhId();
        String name = departmentPullDTO.getOrganization_name();
            JSONObject jsonObject = new JSONObject();

            if(null != name && !"".equals(name)){

                String sql = "select organization_id from organization where organization_name ='" + name + "'";

                 pId  =getReportingToOne(sql);


                json = InternalInterface.getHttp("http://127.0.0.1:8088/rest/orgService/updateOrgName?id="+fhId+"&name="+name+"&pId="+pId+"");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
            return null;
    }

    /**
     * 回调到民师系统
     * @param departmentPullDTO
     * @return
     */
    @Override
    public ResultDTO deleteMhDepartmentInfo(DepartmentCrpPullDTO departmentPullDTO) {

        String id = departmentPullDTO.getFhId();
        try {
             String mhJson="";
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("id",id);
            mhJson = InternalInterface.getHttp("http://127.0.0.1:8088/rest/orgService/delOrg?id="+id+"");

        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 回调oA修改
     * @param departmentPullDTO
     * @return
     */
    @Override
    public ResultDTO updateMhDepartmentInfo(DepartmentCrpPullDTO departmentPullDTO) {

        String organization_id = "";

        String json = "";

        try {
            String fhId = departmentPullDTO.getFhId();

            String name = departmentPullDTO.getOrganization_name();

            if(null != name && !"".equals(name)&&null != fhId && !"".equals(fhId)){

                String sql = "select organization_id from organization where organization_name ='" + name + "'";

                organization_id  =getReportingToOne(sql);

                json = InternalInterface.getHttp("http://127.0.0.1:8088/rest/orgService/updateOrgName?id="+name+"&name="+name+"&pId="+organization_id+"");

            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    /**
     * 从基础平台同步部门数据
     */
    @Override
    public ResultDTO updateDepartmentFromBase() {

        ResultDTO resultDTO = new ResultDTO();

        String sql = "SELECT ORGANISATION_ID,ORGANISATION_NAME,PARENT_ORG_ID FROM fh_rbac_crp.rbac_organisation";
        List<String[]> org_list = new ArrayList<String[]>();
        org_list = getReportingTo(sql);

        int result = 0;
        for(int i=0;i<org_list.size();i++){

            String exist = "SELECT COUNT(1) FROM organization WHERE base_org_id = " +org_list.get(i)[1];
            String exist_num = getReportingToOne(exist);
            if(!exist_num.equals("0")){
                String update = "UPDATE organization SET organization_name = '"+org_list.get(i)[2]+"',PARENT_ORG_ID = "+org_list.get(i)[3]+
                        " WHERE base_org_id = " +org_list.get(i)[1];
                result += addReportingTo(update);
            }else {
                String uuid = UUID.randomUUID().toString().trim().replaceAll("-", "");
                SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                String time = df.format(new Date());
                String insert = "INSERT INTO organization (organization_id,organization_name,organization_state,is_leaf_,create_time_," +
                        "creater_id,sort_no,status,base_org_id,PARENT_ORG_ID) VALUES ('"+uuid+"','"+org_list.get(i)[2]+"',1,'1','"+time+"','"+
                        "1',1,'1',"+org_list.get(i)[1]+","+org_list.get(i)[3]+")";
                result += addReportingTo(insert);
            }
        }
        if (result!=0){
            resultDTO.setStr(result+"");
            resultDTO.setStatus("90000");
            resultDTO.setDescritpion(warnSrc.add_success);
        } else {
            resultDTO.setStatus("90001");
            resultDTO.setDescritpion(warnSrc.add_fail);
        }
        return resultDTO;
    }
}
